package com.qianniu.napi.admin.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.Gstatus;
import com.qianniu.napi.admin.entity.penum.PTstatus;
import com.qianniu.napi.admin.entity.penum.StatusEnum;
import com.qianniu.napi.admin.entity.penum.YXType;
import com.qianniu.napi.admin.mapper.GoodsToupiaoMapper;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.HttpUtil;
import com.qianniu.napi.common.util.ImageUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;

@Configuration
@Component // 此注解必加
@EnableScheduling // 此注解必加
public class GoodsTask {

    private static final Logger logger = LoggerFactory.getLogger(GoodsTask.class);

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBannerService bannerService;
    @Autowired
    private INewsService newsService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private GoodsToupiaoMapper goodsToupiaoMapper;
    @Autowired
    private IPintuanOpenService pintuanOpenService;

    private final static String rootsite = Constants.IMG_UPLOAD_HOST;


    //@Scheduled(cron = "0 7/15 * * * ?")
    public void generateFXimg() {

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>().setSqlSelect("id,pic,mid");
        wrapper.where("state=1");
//        wrapper.where("state=1 and date(createtime)=date(now())");
        Integer index = 1;
        Integer limit = 50;
        boolean flag = true;
        while (flag) {
            Page<Goods> page = goodsService.selectPage(new Page<Goods>(index, limit), wrapper);
            for (Goods good : page.getRecords()) {
                if (Strings.isNullOrEmpty(good.getPic())) continue;

                String srcpic = good.getPic().replace(rootsite, Constants.PATH_IMAGES);
                String targetpic = good.getPic().replace(rootsite, Constants.PATH_GOODS_FENXIANG + "/" + good.getMid());
                String imageType = good.getPic().substring(good.getPic().lastIndexOf(".") + 1);

                if (new File(targetpic).exists()) continue;
                logger.info("====== targetpic=" + targetpic);
                HttpUtil.checkDirectory(targetpic);

                int width = 580, height = 372, start = 0;
                boolean byWidth = true;
                try {

                    BufferedImage originImage = ImageIO.read(new FileInputStream(srcpic));
                    logger.info("originImage width=" + originImage.getWidth() + " height=" + originImage.getHeight());
                    if (originImage.getWidth() / originImage.getHeight() > width / height) {
                        byWidth = false;
                    }

//                    BufferedImage scaleImage = originImage.getWidth() > width ? (
//                            byWidth ? ImageUtil.scaleImageByWidth(new File(srcpic), width) :
//                                    ImageUtil.scaleImageByHeight(new File(srcpic), height)) : originImage;
                    BufferedImage scaleImage = ImageUtil.scaleByPercentage(originImage, width, height);

                    logger.info("scaleImage width=" + scaleImage.getWidth() + " height=" + scaleImage.getHeight());

                    logger.info("==========generateFXimg start write");
                    ImageIO.write(scaleImage, imageType, new File(targetpic));
                    logger.info("==========generateFXimg write over");
                } catch (Exception e) {
                    logger.error("==========generateFXimg error", e);
                }
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
        }
    }

    //    @Scheduled(cron = "0 0/36 * * * ?")
    public void yasuoBannerimg() {

        Wrapper<Banner> wrapper = new EntityWrapper<Banner>().setSqlSelect("id,pic");
//        wrapper.where("state=1");
//        wrapper.where("state=1 and date(createtime)=date(now())");
        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        while (flag) {
            Page<Banner> page = bannerService.selectPage(new Page<Banner>(index, limit), wrapper);
            for (Banner item : page.getRecords()) {

                if (!Strings.isNullOrEmpty(item.getPic())) {
                    String srcpic = item.getPic().replace(rootsite, Constants.PATH_IMAGES);
                    yasuo(srcpic);
                }
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
            logger.info("==========yasuoBannerimg flag=" + flag);
            logger.info("==========yasuoBannerimg index=" + index);
        }
    }

    //    @Scheduled(cron = "0 13 * * * ?")
    public void yasuoNewsimg() {

        Wrapper<News> wrapper = new EntityWrapper<News>().setSqlSelect("id,pic,photos");

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        while (flag) {
            Page<News> page = newsService.selectPage(new Page<News>(index, limit), wrapper);
            for (News item : page.getRecords()) {

                if (!Strings.isNullOrEmpty(item.getPic())) {
                    String img = item.getPic().replace(rootsite, Constants.PATH_IMAGES);
                    yasuo(img, null, null);
                }

                if (!Strings.isNullOrEmpty(item.getPhotos())) {
                    String[] photos = item.getPhotos().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String img : photos) {
                        yasuo(img, null, null);
                    }
                }
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
            logger.info("==========yasuoBannerimg flag=" + flag);
            logger.info("==========yasuoBannerimg index=" + index);
        }
    }

    //    @Scheduled(cron = "0 0/45 * * * ?")
    public void yasuoGoodsimg() {

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>().setSqlSelect("id,thumb,pic,photos,info,packinglist,afterservice,introduction");

        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        while (flag) {
            Page<Goods> page = goodsService.selectPage(new Page<Goods>(index, limit), wrapper);
            for (Goods item : page.getRecords()) {

                if (!Strings.isNullOrEmpty(item.getThumb())) {
                    String img = item.getPic().replace(rootsite, Constants.PATH_IMAGES);
                    yasuo(img, 200, 200);
                }

                if (!Strings.isNullOrEmpty(item.getPic())) {
                    String img = item.getPic().replace(rootsite, Constants.PATH_IMAGES);
                    yasuo(img, null, null);
                }

                if (!Strings.isNullOrEmpty(item.getPhotos())) {
                    String[] photos = item.getPhotos().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String img : photos) {
                        yasuo(img, null, null);
                    }
                }

                if (!Strings.isNullOrEmpty(item.getInfo())) {
                    String[] photos = item.getInfo().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String img : photos) {
                        yasuo(img, null, null);
                    }
                }
                if (!Strings.isNullOrEmpty(item.getPackinglist())) {
                    String[] photos = item.getPackinglist().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String img : photos) {
                        yasuo(img, null, null);
                    }
                }
                if (!Strings.isNullOrEmpty(item.getAfterservice())) {
                    String[] photos = item.getAfterservice().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String img : photos) {
                        yasuo(img, null, null);
                    }
                }
                if (!Strings.isNullOrEmpty(item.getIntroduction())) {
                    String[] photos = item.getIntroduction().replace(rootsite, Constants.PATH_IMAGES).split(";");
                    for (String img : photos) {
                        yasuo(img, null, null);
                    }
                }
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
            logger.info("==========yasuoGoodsimg flag=" + flag);
            logger.info("==========yasuoGoodsimg index=" + index);
        }
    }

    //刷新商品活动状态（每隔5分钟）
    @Scheduled(cron = "0 0/5 * * * ?")
    public void fixGoodsStateRefresh() {

        Wrapper<Goods> wrapper = new EntityWrapper<Goods>().setSqlSelect("id,state,date_end dateEnd");
        wrapper.where(" state=1 and date_end is not null and date_end <= now() ");
        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        while (flag) {
            Page<Goods> page = goodsService.selectPage(new Page<Goods>(index, limit), wrapper);
            for (Goods item : page.getRecords()) {
                item.setStatus(Gstatus.over.getVal());
                item.updateById();

                //更新投票活动状态，如果前十名获奖，设置获奖状态
                if (item.getType() != null && item.getType() == YXType.toupiao.getVal()) {
                    GoodsToupiao goodsToupiao = goodsToupiaoMapper.selectById(item.getId());
                    if (goodsToupiao != null && goodsToupiao.getJiangshu() != null && goodsToupiao.getJiangshu().intValue() > 0) {
                        List<Order> plist = orderService.selectList(new EntityWrapper<Order>()
                                .setSqlSelect("id,goods_number goodsNumber")
                                .eq("state", 1).eq("gid", item.getId()).orderBy("goods_number", false));
                        for (int i = 0; i < plist.size(); i++) {
                            Order norder = new Order();
                            norder.setId(plist.get(i).getId());
                            norder.setModifytime(new Date());
                            if (i < goodsToupiao.getJiangshu().intValue()) {
                                norder.setFhstate(2);//1：进行中；2：投票结束，前几名保留可以核销状态
                            } else {
                                norder.setStatus(StatusEnum.finish.getVal());//后几名直接结束
                            }
                            norder.updateById();
                        }
                    }
                }
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
        }
    }

    //刷新拼团状态（每隔10分钟）
    @Scheduled(cron = "0 0/10 * * * ?")
    public void fixPintuanStateRefresh() {

        Wrapper<PintuanOpen> wrapper = new EntityWrapper<PintuanOpen>().setSqlSelect(" id,status,endtime ");
        wrapper.where(" status= 1 and endtime is not null and endtime<=now() ");//进行中的拼团
        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        while (flag) {
            Page<PintuanOpen> page = pintuanOpenService.selectPage(new Page<PintuanOpen>(index, limit), wrapper);
            for (PintuanOpen item : page.getRecords()) {
                item.setStatus(PTstatus.fail.getVal()); //拼团失败
                item.updateById();
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
        }
    }

    //刷新商家会员级别状态（每隔5分钟）
    @Scheduled(cron = "0 0/13 * * * ?")
    public void storeLevelRefresh() {

        Wrapper<Store> wrapper = new EntityWrapper<Store>().setSqlSelect(" id,mlevel ");
        wrapper.where(" mlevel is null  ");//进行中的拼团
        Integer index = 1;
        Integer limit = 100;
        boolean flag = true;
        while (flag) {
            Page<Store> page = storeService.selectPage(new Page<Store>(index, limit), wrapper);
            for (Store item : page.getRecords()) {

                User user = userService.selectOne(new EntityWrapper<User>()
                        .setSqlSelect("id,member_level memberLevel")
                        .eq("sid", item.getId()).eq("is_staff", -1));
                logger.info("========================storeLevelRefresh user=" + JSON.toJSONString(user));

                if (user == null) continue;
                item.setMlevel(user.getMemberLevel());
                item.updateById();
            }
            flag = page != null && page.getRecords().size() == limit;
            index++;
        }
    }

    private void yasuo(String path) {

        logger.info("------------------------------------yasuo path=" + path);
        File image = new File(path);
        if (!image.exists()) {
            logger.info("------------file not exist for path=" + path);
            return;
        }

        try {
            BufferedImage originImage = ImageIO.read(new FileInputStream(path));
            int width = originImage.getWidth();
            int height = originImage.getHeight();

            if (width <= 800) return;

            logger.info("originImage width=" + originImage.getWidth() + " height=" + originImage.getHeight());
            int w1 = 750;
            int h1 = w1 * height / width;
            Thumbnails.of(path).size(w1, h1).toFile(path);
        } catch (Exception e) {
            logger.error("");
        }

    }

    private void yasuo(String path, Integer w1, Integer h1) {

        File image = new File(path);
        if (!image.exists()) {
            logger.info("------------file not exist for path=" + path);
            return;
        } else {
            logger.info("------------file exist for path=" + path);
        }
        if (path.toLowerCase().lastIndexOf(".png") > 0 ||
                path.toLowerCase().lastIndexOf(".jpg") > 0 ||
                path.toLowerCase().lastIndexOf(".jpeg") > 0) {
            logger.info("------------file is image" + path);
        } else {
            logger.info("------------file is not image");
            return;
        }

        try {
            BufferedImage originImage = ImageIO.read(new FileInputStream(path));
            int width = originImage.getWidth();
            int height = originImage.getHeight();

            if (width <= 750 && w1 == null) return;
            if (w1 != null && width <= w1) return;

            logger.info("------------originImage width=" + originImage.getWidth() + " height=" + originImage.getHeight());
            w1 = (w1 == null) ? 750 : w1;
            h1 = (h1 == null) ? w1 * height / width : h1;
            Thumbnails.of(path).size(w1, h1).toFile(path);
        } catch (Exception e) {
            logger.error("");
        }
    }

}
